package bdz.projects.lavender.cms.managers
{
	import bdz.common.events.XMLLoaderEvent;
	import bdz.projects.lavender.cms.core.CMSGateway;
	import bdz.projects.lavender.cms.model.PluginData;
	
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.utils.clearInterval;
	import flash.utils.setInterval;
	
	import mx.controls.Alert;
	import mx.modules.IModuleInfo;
	import mx.modules.ModuleManager;

	public class PluginManager extends EventDispatcher
	{
		private var gateway:CMSGateway;
		protected var plugins:Array;
		protected var loadcheck:Number;
		public function PluginManager(target:IEventDispatcher=null)
		{
			
			super(target);
			init();
		}
		protected function pluginsLoaded(evt:XMLLoaderEvent):void{
			var xm:XML = new XML(evt.data);
			var plugs:XMLList = xm.ModelPlugin;
			var len:Number = plugs.length();
			for(var i:Number = 0;i<len;i++){
				trace(plugs[i]);
				plugins[i] = new PluginData(plugs[i]);
			}
			dispatchEvent(evt);
		}
		
		private function init():void{
			gateway = CMSGateway.getGateway(CMSGateway.config);
			plugins = new Array();
		}
		
		private function checkPluginLoad(pui:IModuleInfo, plug:PluginData, responder:Function):void{
			if(pui.loaded){
				
				var ui:* = pui.factory.create();
				
				if(ui){ 
					responder(ui, plug.serviceURL);
					clearInterval(plug["inter"]);
				}
			}
		}
		public function getPluginUI(nme:String, responder:Function):Boolean{
			for each(var plugs:PluginData in plugins){
				
				if(plugs.name == nme){
					try{
						var pluginUI:IModuleInfo = ModuleManager.getModule(plugs.pluginClass);
						pluginUI.load();
						
						plugs["inter"] = setInterval(checkPluginLoad, 100, pluginUI, plugs, responder);
					}catch(e:Error){
						Alert.show("Could not create plugin UI information.");
						return false;
					}
					
					return true;
				}
			}
			return false;
		}
		public function getPluginList():Array{
			return plugins.slice();
		}
		public function loadPlugins():void{
			gateway.getPlugins(pluginsLoaded);
		}
		
	}
}